#include <stdio.h>
#include <windows.h>

int main(void)
{
    HANDLE hComm;
    DCB dcb={0};
    COMMTIMEOUTS timeouts={0};
    DWORD bytesRead,bytesWritten;
    char serialport[]="\\\\.\\COM5";

    hComm=CreateFile(serialport,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);

    if(hComm==INVALID_HANDLE_VALUE){
        printf("Failed to open serial port. \n");
        return 1;
    }
    dcb.DCBlength=sizeof(DCB);
    if(!GetCommState(hComm,&dcb)){
        printf("failed to get serial port settings. \n");
        CloseHandle(hComm);
        return 1;
    }

    dcb.BaudRate=CBR_115200;
    dcb.ByteSize=8;
    dcb.Parity=NOPARITY;
    dcb.StopBits=ONESTOPBIT;


    if(!SetCommState(hComm,&dcb)){
        printf("Failed to set serial port settings .\n");
        CloseHandle(hComm);
        return 1;
    }

    timeouts.ReadIntervalTimeout=10;
    timeouts.ReadTotalTimeoutConstant=100;
    timeouts.ReadTotalTimeoutMultiplier=10;
    timeouts.WriteTotalTimeoutConstant=100;
    timeouts.WriteTotalTimeoutMultiplier=10;

    if(!SetCommTimeouts(hComm,&timeouts)){
        printf("Failed to set serail port timeouts . \n");
        CloseHandle(hComm);
        return 1;
    }

    char data[]="Hello,Serial Port";
    if(!WriteFile(hComm,data,sizeof(data),&bytesWritten,NULL)){
        printf("Failed to write data to serial port.\n");
        CloseHandle(hComm);
        return 1;
    }
    char buffer[256];
    if (!ReadFile(hComm, buffer, sizeof(buffer), &bytesRead, NULL))
    {
        printf("Failed to read data from serial port.\n");
        CloseHandle(hComm);
        return 1;
    }

    printf("Received %d bytes: %s\n", bytesRead, buffer);

    CloseHandle(hComm);
    return 0;
}
